今天不看 vue-pure-admin 我們來看一個超簡易範例:
codesandbox 範例連結
其實只要看4個檔案就好了
import { createApp } from 'vue'
import { createPinia } from 'pinia'
import App from './App.vue'
createApp(App).use(createPinia()).mount('#app')
主檔案就是引用 createPinia 將其掛載上去
<template>
  <section>
    <img src="./assets/logo.svg" alt="" width="66" />
    <Counter />
  </section>
</template>
<script>
import Counter from "./pages/counter";
export default {
  name: "App",
  components: {
    Counter,
  },
};
</script>
<style>
#app {
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>
這支只是引用counter.vue 這個 components
接著進入主題,在用pinia之前要引入defineStore,告訴 vue 說我要開始使用 store 囉!
這邊的寫法可以特別記一下 vue-pure-admin 也是這樣用
宣告一個變數(習慣用 use 開頭 和 React 很像)
變數=defineStore('一個專屬id',{ state:()=>{}, getters:{}, actions:{} })
import { defineStore } from "pinia";
export const useCounter = defineStore("counter", {
  //定義有哪些資料
  //可以當成 vue2 的 data 去記
  state: () => ({
    count: 0,
  }),
  //很單純就是操作資料的邏輯
  //可以當成 vue2 的 computed 去記
  getters: {
    doubleCount: (state) => state.count * 2,
    // 若不使用箭頭函數要加 this
    // doubleCount() {
    //   return this.count * 2
    // }
  },
  //方法
  //可以當成 vue2 的 methods 去記
  actions: {
    increment() {
      this.count++;
    },
    decrement() {
      this.count--;
    },
  },
});
最後會 export useCounter 出去 讓外面吃這個變數
終於到最後一個檔案了,這邊引入剛剛輸出的useCounter
再利用專屬的解構方法storeToRefs解出我們定義好的兩個變數
就能在這個components裡面正常使用了!
<template>
  <section>
    <h2>{{ count }}</h2>
    <h2>{{ doubleCount }}</h2>
    <button @click="_handleIncrement">+</button> 
    <!-- 直接寫在 template 也 OK -->
    <button @click="counterStore.decrement()">-</button> 
    <button @click="_handleReset">reset</button>
  </section>
  {{ counterStore }}
  <br />
  {{ counterStore.$state }}
</template>
<!-- Composition API -->
<script setup>
import { useCounter } from "../store/counter";
import { storeToRefs } from "pinia";
const counterStore = useCounter();
const { count, doubleCount } = storeToRefs(counterStore);
/**
 * ❌ 不可這樣寫,要解構需要 pinia 的方法 storeToRefs
 * const { count, doubleCount } = counterStore
 */
function _handleIncrement() {
  counterStore.increment();
  /** 直接操作store数据 */
  //   counterStore.$patch(counterStore.count++);
}
function _handleReset() {
  // 自帶歸零方法
  counterStore.$reset();
}
</script>
<!--  -->
有興趣的讀者不妨試試看開啟 vue devtools 看一下有哪些是自帶的方法呢?
經過今天後我們很快速知道 pinia 的基本用法,之後看 vue-pure-admin 就能更快上手!